package com.ygqh.baby.handler;

import com.ygqh.baby.po.YgDrawPrize;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.YgDrawPrizeService;
import com.ygqh.baby.service.YgUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 〈开奖〉
 *
 * @author guohao
 * @date 2019/1/11 16:12
 * @since 1.0.0
 */
@Component
public class GiftDrawHandler {

    @Autowired
    private YgDrawPrizeService ygDrawPrizeService;
    @Autowired
    private YgUserService ygUserService;


    public Boolean isWinOfNewYearGift(String sourceCode, String openId) {
        YgUser user = ygUserService.findByOpenId(openId);
        if (user == null) {
            return false;
        }
        YgDrawPrize drawPrize = ygDrawPrizeService.findByUserId(user.getId(), sourceCode);
        if (drawPrize == null) {
            return false;
        }
        return drawPrize.getCount() == 10;

    }

    /**
     * 新年有礼开奖
     *
     * @param sourceCode 批次
     * @return 返回用户手机号
     */
    public String drawNewYearGift(String sourceCode) {
        List<YgDrawPrize> list = ygDrawPrizeService.findList(sourceCode);
        //老用户
        List<YgDrawPrize> collect = list.stream().filter(ygDrawPrize -> ygDrawPrize.getRate().compareTo(BigDecimal.ONE) == 0).collect(Collectors.toList());
        Random random = new Random();
        int i = random.nextInt(collect.size());
        YgDrawPrize ygDrawPrize = collect.get(i);
        ygDrawPrize.setCount(10);
        ygDrawPrize.setUpdateTime(new Date());
        ygDrawPrize.setUpdateBy("开奖");
        ygDrawPrizeService.update(ygDrawPrize);
        return ygDrawPrize.getRemark();
    }

}
